<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Socket.IO 测试</title>
</head>

<body>
    <h1>Socket.IO 前端测试</h1>
    <p id="status">未连接</p>
    <div id="container">
        <p></p>
    </div>

    <!-- 使用非模块化版本的 Socket.IO 客户端库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.8.1/socket.io.js"></script>
    <script>
        const CharArr = []
        const container = document.getElementById('container')
        // 连接到服务器
        const socket = io('http://localhost:6012', {
            extraHeaders: {
                authorization: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMTA2Mjk0YjEtY2QyOC00ZDViLWIyZjMtODFkYjBmZjJlYTZjIiwidXNlcl9uaWNrbmFtZSI6IueUqOaItzIiLCJ1c2VyX2VtYWlsIjoiNzY2OTgyMzUyQHFxLmNvbSIsImltYWdlIjoiaHR0cDovL3NreXByby5hZnRlcmdsb3cyNi5jbjoyODA4MC9pLzIwMjQvMTAvMjkvNjcyMDhhNGU3NDYyOS5qcGciLCJpbWFnZWtleSI6IkNpMFl2MiIsImlhdCI6MTczMDcyMzI2MCwiZXhwIjoxNzMwODA5NjYwfQ.hUdyZ-Gg-rXzbXbiZklWXkAuIz_iAZ7rEn_giYrMEPM"
            }
        });
        const statusElement = document.getElementById('status');

        // 监听连接成功事件
        socket.on('connect', () => {
            console.log('连接成功');
            statusElement.textContent = '已连接';
        });

        // 发送测试消息
        socket.emit('chat', '前端消息测试');
        socket.emit('photo', '发送图片');

        // 监听服务器返回的消息


        socket.on('privateChat', (params) => {
            container.innerHTML = ''
            const { sendid, message } = params
            CharArr.push({ sendid, message })
            console.log(CharArr);

            CharArr.forEach((item) => {
                const p = document.createElement('p')
                const span = document.createElement('span')
                span.innerHTML = `发送人: ${item.sendid} <p>${item.message}</p>`
                container.appendChild(span)
            })

        })
        // 监听断开事件
        socket.on('disconnect', () => {
            console.log('断开连接');
            statusElement.textContent = '连接已断开';
        });


    </script>
</body>

</html>